/*
 * RacesTable.java
 *
 * Created on November 6, 2007, 10:50 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package jia.editor.widgets;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import jia.editor.EditorMain;
import jia.editor.lists.pnl_CreatureList;
import jia.persist.Creature;
import org.apache.log4j.Logger;


/**
 *
 * @author estell
 */
public class CreaturesTable extends JTable{
    private static final Logger log = Logger.getLogger(CreaturesTable.class);
    JPopupMenu tblPop = new JPopupMenu();
    pnl_CreatureList creatureList;
    static List dataList;
    
    static{
        try {
            
            //get the data for this table (to be used later)
            EditorMain.sqlMap.startTransaction();
            dataList = EditorMain.sqlMap.queryForList("getCreatures");
            EditorMain.sqlMap.commitTransaction();
            log.error("Connection loaded!");
        } catch (SQLException ex) {
            log.error(ex);
            
        }
        
    }
    
    /** Creates a new instance of RacesTable */
    public CreaturesTable(pnl_CreatureList newCreatureList) {
        super();
        //set a pointer to this tables parent JPanel
        this.creatureList = newCreatureList;
        
        
        
        //set the table model for this table
        this.setModel(new CreaturesTableModel());
        
        //set a few minor flags to prevent unexpected behavior
        this.setCellSelectionEnabled(false);
        this.setRowSelectionAllowed(true);
        this.setColumnSelectionAllowed(false);
        this.setDragEnabled(false);
        this.getTableHeader().setReorderingAllowed(false);
        this.setShowGrid(true);
        this.setGridColor(Color.GRAY);
        
        //make sure only one row at a time can be selected
        this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        //add items to the tables pop-up menu
        JMenuItem editMnuItem = new JMenuItem("Edit");
        editMnuItem.addActionListener(new CreatureEditRowsActionAdapter(this));
        editMnuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/add.png")));
        tblPop.add(editMnuItem);
        
        JMenuItem deleteMnuItem = new JMenuItem("Delete");
        deleteMnuItem.addActionListener(new CreatureDeleteRowsActionAdapter(this));
        deleteMnuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jia_ui/images/add.png")));
        tblPop.add(deleteMnuItem);
        
        //create and register this table's popup listener
        MouseListener popupListener = new CeaturePopListener(this);
        this.addMouseListener(popupListener);
        
    }
    
    //custom listener object for mouse actions
    class CeaturePopListener extends MouseAdapter {
        CreaturesTable adaptee;
        
        CeaturePopListener(CreaturesTable adaptee){
            this.adaptee = adaptee;
        }
        public void mousePressed(MouseEvent e) {
            showPopup(e);
        }
        
        public void mouseClicked(MouseEvent e){
            if (e.getClickCount() == 2){
                int rowIndex = adaptee.rowAtPoint(e.getPoint());
                creatureList.setConsoleText("Double Clicked on row number: " + rowIndex);
            }
        }
        public void mouseReleased(MouseEvent e) {
            showPopup(e);
        }
        private void showPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                int rowIndex = adaptee.rowAtPoint(e.getPoint());
                adaptee.setRowSelectionInterval(rowIndex, rowIndex);
                tblPop.show(e.getComponent(), e.getX(), e.getY());
                
            }
        }
    }
    
    //special action for the pop up menu's Edit command
    class CreatureEditRowsActionAdapter implements ActionListener {
        CreaturesTable adaptee;
        
        CreatureEditRowsActionAdapter(CreaturesTable adaptee) {
            this.adaptee = adaptee;
        }
        public void actionPerformed(ActionEvent e) {
            creatureList.setConsoleText("The following row was selected: " + adaptee.getValueAt(adaptee.getSelectedRow(), 0));
            //TODO:  call panel swapper to load the race editor screen.
        }
    }
    
    //special action for the pop up menu's delete command
    class CreatureDeleteRowsActionAdapter implements ActionListener {
        CreaturesTable adaptee;
        
        CreatureDeleteRowsActionAdapter(CreaturesTable adaptee) {
            this.adaptee = adaptee;
        }
        public void actionPerformed(ActionEvent e) {
            creatureList.setConsoleText("The following row was selected: " + adaptee.getValueAt(adaptee.getSelectedRow(), 0));
            //TODO:  call the process that will remove this race
        }
    }
    
    //custom table model that handles the data
    class CreaturesTableModel extends AbstractTableModel{
        private Vector<Object[]> dataRows;
        private boolean DEBUG = false;
        
        private String[] columnNames = { "ID", "Name", "Type", "Size", "Challenge Rating", "Enabled"};
        
        
        //make sure none of the columns are editable
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false
        };
        
        //make sure none of the individual cells are editable
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
        
        //pulls the value of a cell
        public Object getValueAt(int row, int col) {
            Creature thisCreature = (Creature)dataList.get(row);
            Object retVal = null;
            if (col == 0){
                retVal = thisCreature.getCREATURE_ID();
            }else if(col == 1){
                retVal = thisCreature.getCREATURE_NAME();
                
            }else if(col == 2){
                retVal = thisCreature.getCREATURE_TYPE();
                
            }else if(col == 3){
                retVal = thisCreature.getCREATURE_SIZE();
                
            }else if(col == 4){
                retVal = thisCreature.getCHALLENGE_RATING();
                
            }else if (col == 5){
                if (thisCreature.getISENABLED() == 1){
                    retVal = new Boolean(true);
                }else{
                    retVal = new Boolean(false);
                }
                
            }
            
            return retVal;
            
        }
        
        //returns the number of columns
        public int getColumnCount() {
            return columnNames.length;
        }
        
        //returns the number of rows
        public int getRowCount() {
            return dataList.size();
        }
        
        //gets the name of the column
        public String getColumnName(int col) {
            return columnNames[col];
        }
        
        /*
         * JTable uses this method to determine the default renderer/ editor for
         * each cell. If we didn't implement this method, then the last column
         * would contain text ("true"/"false"), rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
        
        /*
         * Don't need to implement this method unless your table's data can
         * change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                    + " to " + value + " (an instance of "
                    + value.getClass() + ")");
            }
            
            dataList.set(row, value);
            fireTableCellUpdated(row, col);
            
            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }
        
        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();
            
            for (int i = 0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    //System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }
}